<?php
/**
 * @Author:      Zy
 * @DateTime:    2018-5-09 15:32:48
 * @Description: 用于 pms 订货单,采购单统计
 */
class PMSStatisController extends BaseController {
    /**
     *  订货分析
     * */
    public function planProductsList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'date_start' => 'required',
                'date_end' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $date_start = Input::get("date_start");
            $date_end = Input::get("date_end");
            $shop_id = Input::get("shop_id");
            $supplier_id = Input::get("supplier_id");
            $plan_status = Input::get("plan_status"); //1拼货中  2待收货  3 已收货
            $ratio_type = Input::get("ratio_type",1); //1:总占比  2：上级占比 
            
            //耗材的搜索
            $level_1 = Input::get("level_1");
            $level_2 = Input::get("level_2");
            $level_3 = Input::get("level_3");
            $item = Input::get("item");
            $brand = Input::get("brand");
            //供应商搜索
            $supplier_status = Input::get("supplier_status");//供应商关键字搜索
            $supplier_str = Input::get("supplier_str");//供应商关键字搜索
            $supplier_city = Input::get("supplier_city"); //商业 市
            $supplier_region = Input::get("supplier_region"); //商业 区
            //下面的筛选门店
            $shop_city = Input::get("shop_city");// 门店 市
            $shop_region = Input::get("shop_region");// 门店 区

            //订货单相关纤细
            $plan_list = PMSPlanProducts::select("pms_plan_products.*","ppo.submit_at","ppo.pay_type","ppo.status as plan_status")->where("pms_plan_products.is_split",0)->where("pms_plan_products.status",3)->where("ppo.submit_at",">=",$date_start." 00:00:00")->where("ppo.submit_at","<=",$date_end." 23:59:59");
            $plan_list->leftJoin("pms_plan_order as ppo","ppo.plan_code","=","pms_plan_products.plan_code");
            if($shop_id != "")$plan_list->where("ppo.shop_id",$shop_id);
            if($supplier_id !="" ) $plan_list->where("ppo.supplier_id",$supplier_id);
            if($plan_status != "") $plan_list->where("ppo.status",$plan_status);
            
            //耗材相关信息
            $plan_list->addSelect("sc3.name as sc3_name","sc3.id as sc3_id","sc2.name as sc2_name","sc2.id as sc2_id","sc1.name as sc1_name","sc1.id as sc1_id","si.name as si_name","si.id as si_id","si.brand_name as si_brand_name","si.brand_id as si_brand_id","si.code as si_code")
                    ->leftJoin("supply_item as si","pms_plan_products.product_id","=","si.id")
                    ->leftJoIn("supply_classification as sc3","sc3.id","=","si.supply_classification_id")
                    ->leftJoIn("supply_classification as sc2","sc2.id","=","sc3.parent_id")
                    ->leftJoIn("supply_classification as sc1","sc1.id","=","sc2.parent_id");
                if($level_1 != "")  $plan_list ->where("sc1.id",$level_1);
                if($level_2 != "")  $plan_list ->where("sc2.id",$level_2);
                if($level_3 != "")  $plan_list ->where("sc3.id",$level_3);
                if($item != "" ) $plan_list->where("si.retrieval_code","like",'%'.$item.'%');
                if($brand != "") $plan_list->where("si.retrieval_code","like",'%'.$brand.'%');
            
            //供应商相关信息
            $plan_list->addSelect("ms.name as ms_name","ms.city_id as ms_city_id","ms.region_id as ms_region_id","ppo.supplier_id")
                    ->leftJoin("maintenance_supplier as ms","ms.id","=","ppo.supplier_id"); 
            if ($supplier_str!="") $plan_list->where("ms.name","like",'%'.$supplier_str.'%');
            if ($supplier_city !="") $plan_list->where("ms.city_id",$supplier_city);
            if ($supplier_region !="") $plan_list->where("ms.region_id",$supplier_region);
            if ($supplier_status !="") $plan_list->where("ms.purchase_status",$supplier_status);
                
            //门店相关信息
            $plan_list->addSelect("shop.name as shop_name","shop.city_id as shop_city_id","shop.region_id as shop_region_id","ppo.shop_id")
                    ->leftJoin("maintenance_shops as shop","ppo.shop_id","=","shop.id");
            if ($shop_city !="") $plan_list->where("shop.city_id",$shop_city);
            if ($shop_region !="") $plan_list->where("shop.region_id",$shop_region); 
            
            
            $level_redio = [];
            $city_redio = [];
            $count = ["receive_num" => 0, //签收总计
                    "receive_tax_purchase_price" => 0, //签收总金额
                    "not_receive_num" => 0, //未签总计
                    "not_receive_tax_purchase_price" => 0,//未签收总金额
                ];
            if ($plan_list->count() == 0) {
                $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>"",'plan_products_status'=>PMSPlanOrder::$status,'pay_type'=>PMSPlanOrder::$pay_type,'level_redio'=>"",'city_redio'=>"",'count'=>  ""]);
                return $response;
                break;
            }
            
            $list = $plan_list->get();
            foreach ($list as $_list) {
                //基础数据赋值
                $receive = PMSReceiveProductsResult::where("plan_code",$_list->plan_code)->where("product_id",$_list->product_id)->where("type",6)->sum("num");
                $_list->receive_num = $receive;
                $_list->not_receive_num = $_list->all_num - $_list->receive_num;
                $_list->tax_purchase_price = round($_list->tax_purchase_price/100,2);
                
                $all_tax_purchase_price = round($_list->tax_purchase_price*$_list->receive_num,2);
                $_list->receive_tax_purchase_price = $all_tax_purchase_price;
                $all_not_tax_purchase_price = round($_list->tax_purchase_price*$_list->not_receive_num,2); //未签进小计
                $_list->not_receive_tax_purchase_price = $all_not_tax_purchase_price;
                
                $count["receive_num"] += $_list->receive_num;
                $count["not_receive_num"] += $_list->not_receive_num;
                $count["receive_tax_purchase_price"] += $_list->receive_tax_purchase_price; 
                $count["not_receive_tax_purchase_price"] += $_list->not_receive_tax_purchase_price; 
            }

            $level_redio = $this->levelRedio($list,$ratio_type,$count);
            $city_redio = $this->cityRedio($list,$ratio_type,$count);
            
             $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>$list,'plan_products_status'=>PMSPlanOrder::$status,'pay_type'=>PMSPlanOrder::$pay_type,'level_redio'=>$level_redio,'city_redio'=>$city_redio,'count'=>  $count]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "PMSStatis/planProductsList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @deprecated 分类明细处理
     * @param $list 需要统计的数组
     * @param $type 统计的类型
     * @param $count 总数量的集合
     * 
     **/
    private function levelRedio($list,$ratio_type,$count) {
        $level_redio = [];
        //$level_redio = ["level_1"][0]["name"=>"分类1"]["level_2"][0]["name"=>"分类2"][0]["name"=>"分类3"];
        $basic_arr = ["receive_num"=> 0 , //定义每一层基本的结构
                    "receive_tax_purchase_price"=> 0,
                    "not_receive_num"=> 0 ,
                    "not_receive_tax_purchase_price"=> 0,
                    "name"=>"",
            ];
        foreach ($list as $_list) {
                //统计基础数据
                if (!isset($level_redio[$_list->sc1_id])) {
                    $level_redio[$_list->sc1_id]= $basic_arr;
                    $level_redio[$_list->sc1_id]["name"] = $_list->sc1_name;
                }
                if(!isset($level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id])){
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id] = $basic_arr;
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["name"] = $_list->sc2_name;
                }
                if (!isset($level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id])){
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id] = $basic_arr;
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id]["name"] = $_list->sc3_name;;
                } 
                //三级   
                $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id]["receive_num"] += $_list->receive_num;
                $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id]["receive_tax_purchase_price"] += $_list->receive_tax_purchase_price;
                $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id]["not_receive_num"] += $_list->not_receive_num;
                $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id]["not_receive_tax_purchase_price"] += $_list->not_receive_tax_purchase_price;
                
                //二级
                $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["receive_num"] += $_list->receive_num;
                $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["receive_tax_purchase_price"] += $_list->receive_tax_purchase_price;
                $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["not_receive_num"] += $_list->not_receive_num;
                $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["not_receive_tax_purchase_price"] += $_list->not_receive_tax_purchase_price;
                //一级
                $level_redio[$_list->sc1_id]["receive_num"] += $_list->receive_num;
                $level_redio[$_list->sc1_id]["receive_tax_purchase_price"] += $_list->receive_tax_purchase_price;   
                $level_redio[$_list->sc1_id]["not_receive_num"] += $_list->not_receive_num;
                $level_redio[$_list->sc1_id]["not_receive_tax_purchase_price"] += $_list->not_receive_tax_purchase_price;   
        }
        
        if ($ratio_type == 1) { //上级占比 占上级总数的百分之多少
            foreach ($level_redio as $level_1_id => $level_1_value) {
                foreach ($level_1_value["level_2"] as $level_2_id => $level_2_value) {
                    foreach ($level_2_value["level_3"] as $level_3_id => $level_3_value) {
                        //三级签收统计
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_receive_num"] = $count['receive_num'] == 0 ? 0:
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["receive_num"]/$count['receive_num']*100);
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_receive_tax_purchase_price"] = $count['receive_tax_purchase_price'] == 0 ? 0:
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["receive_tax_purchase_price"]/$count['receive_tax_purchase_price']*100);
                        //三级未签收统计
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_not_receive_num"] = $count['not_receive_num'] == 0 ? 0:
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["not_receive_num"]/$count['not_receive_num']*100);
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_not_receive_tax_purchase_price"] = $count['not_receive_tax_purchase_price'] == 0 ? 0 :
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["not_receive_tax_purchase_price"]/$count['not_receive_tax_purchase_price']*100);
                    }
                    
                    //二级签收统计
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_receive_num"] = $count['receive_num'] == 0 ? 0 :
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["receive_num"]/$count['receive_num']*100);
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_receive_tax_purchase_price"] =  $count['receive_tax_purchase_price'] == 0 ? 0:
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["receive_tax_purchase_price"]/$count['receive_tax_purchase_price']*100);
                    //二级未签收统计
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_not_receive_num"] = $count['not_receive_num'] == 0 ? 0 :
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["not_receive_num"]/$count['not_receive_num']*100);
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_not_receive_tax_purchase_price"] = $count['not_receive_tax_purchase_price'] == 0 ? 0 :
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["not_receive_tax_purchase_price"]/$count['not_receive_tax_purchase_price']*100);
                }
            //一级签收统计
            $level_redio[$level_1_id]["redio_receive_num"] = $count['receive_num']==0 ? 0 : round($level_redio[$level_1_id]["receive_num"]/$count['receive_num']*100);
            $level_redio[$level_1_id]["redio_receive_tax_purchase_price"] =  $count['receive_tax_purchase_price'] == 0 ? 0: round($level_redio[$level_1_id]["receive_tax_purchase_price"]/$count['receive_tax_purchase_price']*100);
            //一级未签收统计
            $level_redio[$level_1_id]["redio_not_receive_num"] = $count['not_receive_num'] == 0 ? 0 :round($level_redio[$level_1_id]["not_receive_num"]/$count['not_receive_num']*100);
            $level_redio[$level_1_id]["redio_not_receive_tax_purchase_price"] = $count['not_receive_tax_purchase_price'] == 0 ? 0 : round($level_redio[$level_1_id]["not_receive_tax_purchase_price"]/$count['not_receive_tax_purchase_price']*100);   
            }
        }
        
    
        if ($ratio_type == 2) {
            foreach ($level_redio as $level_1_id => $level_1_value) {
                foreach ($level_1_value["level_2"] as $level_2_id => $level_2_value) {
                    foreach ($level_2_value["level_3"] as $level_3_id => $level_3_value) {
                        //三级签收统计
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_receive_num"] = $level_redio[$level_1_id]["level_2"][$level_2_id]["receive_num"] == 0? 0:
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["receive_num"]/$level_redio[$level_1_id]["level_2"][$level_2_id]["receive_num"]*100);
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_receive_tax_purchase_price"] = $level_redio[$level_1_id]["level_2"][$level_2_id]['receive_tax_purchase_price'] == 0? 0: 
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["receive_tax_purchase_price"]/$level_redio[$level_1_id]["level_2"][$level_2_id]['receive_tax_purchase_price']*100);
                        //三级未签收统计
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_not_receive_num"] = $level_redio[$level_1_id]["level_2"][$level_2_id]['not_receive_num'] == 0 ?0:
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["not_receive_num"]/$level_redio[$level_1_id]["level_2"][$level_2_id]['not_receive_num']*100);
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_not_receive_tax_purchase_price"] = $level_redio[$level_1_id]["level_2"][$level_2_id]['not_receive_tax_purchase_price'] == 0 ? 0 :
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["not_receive_tax_purchase_price"]/$level_redio[$level_1_id]["level_2"][$level_2_id]['not_receive_tax_purchase_price']*100);
                    }
                    
                    //二级签收统计
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_receive_num"] = $level_redio[$level_1_id]['receive_num'] == 0 ?0 :
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["receive_num"]/$level_redio[$level_1_id]['receive_num']*100);
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_receive_tax_purchase_price"] = $level_redio[$level_1_id]['receive_tax_purchase_price'] == 0 ? 0 :
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["receive_tax_purchase_price"]/$level_redio[$level_1_id]['receive_tax_purchase_price']*100);
                    //二级未签收统计
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_not_receive_num"] = $level_redio[$level_1_id]['not_receive_num'] == 0 ? 0 :
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["not_receive_num"]/$level_redio[$level_1_id]['not_receive_num']*100);
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_not_receive_tax_purchase_price"] = $level_redio[$level_1_id]['not_receive_tax_purchase_price'] == 0 ? 0 : 
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["not_receive_tax_purchase_price"]/$level_redio[$level_1_id]['not_receive_tax_purchase_price']*100);
                }
            //一级签收统计
            $level_redio[$level_1_id]["redio_receive_num"] = 100;
            $level_redio[$level_1_id]["redio_receive_tax_purchase_price"] = 100;
            //一级未签收统计
            $level_redio[$level_1_id]["redio_not_receive_num"] = 100;
            $level_redio[$level_1_id]["redio_not_receive_tax_purchase_price"] = 100;
            }
        }
        
        $level_redio_object = [];
        //将数组转换成对象
            foreach ($level_redio as $level_1_id => $level_1_value) {
                $level_redio_object[$level_1_id] = $level_1_value;
                foreach ($level_1_value["level_2"] as $level_2_id => $level_2_value) {
                    $level_redio_object[$level_1_id]["level_2"][$level_2_id] = $level_2_value;
                    $level_redio_object[$level_1_id]["level_2"][$level_2_id]["level_3"] = array_values($level_2_value["level_3"]);
                }
                $level_redio_object[$level_1_id]["level_2"] = array_values($level_redio_object[$level_1_id]["level_2"]);
            }
        
        return array_values($level_redio_object);
    }

    /**
     * @deprecated 城市明细处理
     * @param $list 需要统计的数组
     * @param $type 统计的类型
     * @param $count 总数量的集合
     * 
     **/
    private function cityRedio($list,$ratio_type,$count) {
        $city_redio = [];
        $basic_arr = ["receive_num"=> 0 , //定义每一层基本的结构
                    "receive_tax_purchase_price"=> 0,
                    "not_receive_num"=> 0 ,
                    "not_receive_tax_purchase_price"=> 0,
                    "name"=>"",
            ];
        foreach ($list as $_list) {
                //统计基础数据
                if (!isset($city_redio[$_list->shop_city_id])) {
                    $city_redio[$_list->shop_city_id]= $basic_arr;
                    $city = DataResourceCity::where("id",$_list->shop_city_id)->first();
                    $city_redio[$_list->shop_city_id]["name"] = isset($city->city_name) ? $city->city_name :"";
                }
                if(!isset($city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id])){
                    $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id] = $basic_arr;
                    $region = DataResourceRegion::where("id",$_list->shop_region_id)->first();
                    $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["name"] = isset($region->region_name) ? $region->region_name:"";
                }
                if (!isset($city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id])){
                    $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id] = $basic_arr;
                    $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id]["name"] = $_list->shop_name;;
                } 
                //店 
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id]["receive_num"] += $_list->receive_num;
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id]["receive_tax_purchase_price"] += $_list->receive_tax_purchase_price;
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id]["not_receive_num"] += $_list->not_receive_num;
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id]["not_receive_tax_purchase_price"] += $_list->not_receive_tax_purchase_price;
                
                //区
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["receive_num"] += $_list->receive_num;
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["receive_tax_purchase_price"] += $_list->receive_tax_purchase_price;
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["not_receive_num"] += $_list->not_receive_num;
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["not_receive_tax_purchase_price"] += $_list->not_receive_tax_purchase_price;
                //市
                $city_redio[$_list->shop_city_id]["receive_num"] += $_list->receive_num;
                $city_redio[$_list->shop_city_id]["receive_tax_purchase_price"] += $_list->receive_tax_purchase_price;   
                $city_redio[$_list->shop_city_id]["not_receive_num"] += $_list->not_receive_num;
                $city_redio[$_list->shop_city_id]["not_receive_tax_purchase_price"] += $_list->not_receive_tax_purchase_price;   
        }
        
        if ($ratio_type == 1) { //上级占比 占上级总数的百分之多少
            foreach ($city_redio as $city_id => $city_value) {
                foreach ($city_value["region"] as $region_id => $region_value) {
                    foreach ($region_value["shop"] as $shop_id => $shop_value) {
                        //店 签收统计
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_receive_num"] = $count['receive_num'] == 0 ? 0:
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["receive_num"]/$count['receive_num']*100);
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_receive_tax_purchase_price"] = $count['receive_tax_purchase_price'] == 0 ? 0:
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["receive_tax_purchase_price"]/$count['receive_tax_purchase_price']*100);
                        //店 未签收统计
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_not_receive_num"] = $count['not_receive_num'] == 0 ? 0:
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["not_receive_num"]/$count['not_receive_num']*100);
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_not_receive_tax_purchase_price"] = $count['not_receive_tax_purchase_price'] == 0 ? 0 :
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["not_receive_tax_purchase_price"]/$count['not_receive_tax_purchase_price']*100);
                    }
                    
                    //区签收统计
                    $city_redio[$city_id]["region"][$region_id]["redio_receive_num"] = $count['receive_num'] == 0 ? 0 :
                            round($city_redio[$city_id]["region"][$region_id]["receive_num"]/$count['receive_num']*100);
                    $city_redio[$city_id]["region"][$region_id]["redio_receive_tax_purchase_price"] =  $count['receive_tax_purchase_price'] == 0 ? 0:
                            round($city_redio[$city_id]["region"][$region_id]["receive_tax_purchase_price"]/$count['receive_tax_purchase_price']*100);
                    //区未签收统计
                    $city_redio[$city_id]["region"][$region_id]["redio_not_receive_num"] = $count['not_receive_num'] == 0 ? 0 :
                            round($city_redio[$city_id]["region"][$region_id]["not_receive_num"]/$count['not_receive_num']*100);
                    $city_redio[$city_id]["region"][$region_id]["redio_not_receive_tax_purchase_price"] = $count['not_receive_tax_purchase_price'] == 0 ? 0 :
                            round($city_redio[$city_id]["region"][$region_id]["not_receive_tax_purchase_price"]/$count['not_receive_tax_purchase_price']*100);
                }
            //市签收统计
            $city_redio[$city_id]["redio_receive_num"] = $count['receive_num']==0 ? 0 : round($city_redio[$city_id]["receive_num"]/$count['receive_num']*100);
            $city_redio[$city_id]["redio_receive_tax_purchase_price"] =  $count['receive_tax_purchase_price'] == 0 ? 0: round($city_redio[$city_id]["receive_tax_purchase_price"]/$count['receive_tax_purchase_price']*100);
            //市未签收统计
            $city_redio[$city_id]["redio_not_receive_num"] = $count['not_receive_num'] == 0 ? 0 :round($city_redio[$city_id]["not_receive_num"]/$count['not_receive_num']*100);
            $city_redio[$city_id]["redio_not_receive_tax_purchase_price"] = $count['not_receive_tax_purchase_price'] == 0 ? 0 : round($city_redio[$city_id]["not_receive_tax_purchase_price"]/$count['not_receive_tax_purchase_price']*100);   
            }
        }
        
    
        if ($ratio_type == 2) {
            foreach ($city_redio as $city_id => $city_value) {
                foreach ($city_value["region"] as $region_id => $region_value) {
                    foreach ($region_value["shop"] as $shop_id => $shop_value) {
                        //店 签收统计
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_receive_num"] = $city_redio[$city_id]["region"][$region_id]["receive_num"] == 0? 0:
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["receive_num"]/$city_redio[$city_id]["region"][$region_id]["receive_num"]*100);
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_receive_tax_purchase_price"] = $city_redio[$city_id]["region"][$region_id]['receive_tax_purchase_price'] == 0? 0: 
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["receive_tax_purchase_price"]/$city_redio[$city_id]["region"][$region_id]['receive_tax_purchase_price']*100);
                        //店 未签收统计
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_not_receive_num"] = $city_redio[$city_id]["region"][$region_id]['not_receive_num'] == 0 ?0:
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["not_receive_num"]/$city_redio[$city_id]["region"][$region_id]['not_receive_num']*100);
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_not_receive_tax_purchase_price"] = $city_redio[$city_id]["region"][$region_id]['not_receive_tax_purchase_price'] == 0 ? 0 :
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["not_receive_tax_purchase_price"]/$city_redio[$city_id]["region"][$region_id]['not_receive_tax_purchase_price']*100);
                    }
                    
                    //区签收统计
                    $city_redio[$city_id]["region"][$region_id]["redio_receive_num"] = $city_redio[$city_id]['receive_num'] == 0 ?0 :
                            round($city_redio[$city_id]["region"][$region_id]["receive_num"]/$city_redio[$city_id]['receive_num']*100);
                    $city_redio[$city_id]["region"][$region_id]["redio_receive_tax_purchase_price"] = $city_redio[$city_id]['receive_tax_purchase_price'] == 0 ? 0 :
                            round($city_redio[$city_id]["region"][$region_id]["receive_tax_purchase_price"]/$city_redio[$city_id]['receive_tax_purchase_price']*100);
                    //区未签收统计
                    $city_redio[$city_id]["region"][$region_id]["redio_not_receive_num"] = $city_redio[$city_id]['not_receive_num']==0 ? 0 :
                            round($city_redio[$city_id]["region"][$region_id]["not_receive_num"]/$city_redio[$city_id]['not_receive_num']*100);
                    $city_redio[$city_id]["region"][$region_id]["redio_not_receive_tax_purchase_price"] = $city_redio[$city_id]['not_receive_tax_purchase_price'] == 0 ? 0 : 
                            round($city_redio[$city_id]["region"][$region_id]["not_receive_tax_purchase_price"]/$city_redio[$city_id]['not_receive_tax_purchase_price']*100);
                }
            //市签收统计
            $city_redio[$city_id]["redio_receive_num"] = 100;
            $city_redio[$city_id]["redio_receive_tax_purchase_price"] = 100;
            //市未签收统计
            $city_redio[$city_id]["redio_not_receive_num"] = 100;
            $city_redio[$city_id]["redio_not_receive_tax_purchase_price"] = 100;
            }
        }
        
        $city_redio_object = [];
        //将数组转换成对象
            foreach ($city_redio as $city_id => $city_value) {
                $city_redio_object[$city_id] = $city_value;
                foreach ($city_value["region"] as $region_id => $region_value) {
                    $city_redio_object[$city_id]["region"][$region_id] = $region_value;
                    $city_redio_object[$city_id]["region"][$region_id]["shop"] = array_values($region_value["shop"]);
                }
                $city_redio_object[$city_id]["region"] = array_values($city_redio_object[$city_id]["region"]);
            }
        
        return array_values($city_redio_object);
    }

    /**
     *  采购分析
     * */
    public function StorageItemList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'date_start' => 'required',
                'date_end' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $date_start = Input::get("date_start");
            $date_end = Input::get("date_end");
            $shop_id = Input::get("shop_id");
            $supplier_id = Input::get("supplier_id");
            $list_type = Input::get("list_type"); //1:购入  2：退货 
            $ratio_type = Input::get("ratio_type",1); //1:总占比  2：上级占比 
            
            //耗材的搜索
            $level_1 = Input::get("level_1");
            $level_2 = Input::get("level_2");
            $level_3 = Input::get("level_3");
            $item = Input::get("item");
            $brand = Input::get("brand");
            //供应商搜索
            $supplier_status = Input::get("supplier_status");//供应商关键字搜索
            $supplier_str = Input::get("supplier_str");//供应商关键字搜索
            $supplier_city = Input::get("supplier_city"); //商业 市
            $supplier_region = Input::get("supplier_region"); //商业 区
            //下面的筛选门店
            $shop_city = Input::get("shop_city");// 门店 市
            $shop_region = Input::get("shop_region");// 门店 区
            $date_start .= " 00:00:00";
            $date_end .= " 23:59:59";
            
            $sql_1 = "select msi.item_type,msi.item_id,maintenance_storage_list.implement_time,maintenance_storage_list.shop_id,msi.`code`,msi.`name`,msi.number,msi.tax_purchase_price,msi.tax_purchase_subtotal,maintenance_storage_list.pay_type ,msi.data_id,msi.no_tax_purchase_price,1 as list_type,maintenance_storage_list.supplier
            FROM maintenance_storage_item msi
            LEFT JOIN maintenance_storage_list ON msi.list_id = maintenance_storage_list.id
            WHERE  `maintenance_storage_list`.`implement_time` BETWEEN '".$date_start."' AND '".$date_end."' AND `maintenance_storage_list`.`status` = 1 
            AND `msi`.`status` = 1 
            AND `maintenance_storage_list`.`type` IN (1, 2)";  //入库单
            
            $sql_2 = "SELECT  moi.item_type,moi.item_id,maintenance_out_list.implement_time,maintenance_out_list.shop_id,moi.`code`,moi.`name`,moi.number,moi.tax_purchase_price,moi.tax_purchase_subtotal,maintenance_out_list.pay_type,moi.data_id,moi.no_tax_purchase_price,2 as list_type,maintenance_out_list.consuming_id as supplier
            FROM
                maintenance_out_item moi
            LEFT JOIN maintenance_out_list ON moi.list_id = maintenance_out_list.id
            WHERE
                maintenance_out_list.implement_time BETWEEN '".$date_start."' AND '".$date_end.
            "' AND `maintenance_out_list`.`status` = 1
            AND `moi`.`status` = 1
            AND `maintenance_out_list`.`type` = 2
            AND `maintenance_out_list`.`out_type` = 2";   //退货单
            //入库单相关
            $sql = "SELECT a.*,sc3.name as sc3_name,sc3.id as sc3_id,sc2.name as sc2_name,sc2.id as sc2_id,sc1.name as sc1_name,sc1.id as sc1_id,si.name as si_name,si.id as si_id,si.brand_name as si_brand_name,si.brand_id as si_brand_id,si.code as si_code,ms.name as ms_name,ms.city_id as ms_city_id,ms.region_id as ms_region_id,shop.name as shop_name,shop.city_id as shop_city_id,shop.region_id as shop_region_id";
            if ($list_type == 1) {
                $sql .= " from ($sql_1) a ";
            }elseif($list_type == 2){
                $sql .= " from ($sql_2) a ";
            }else{
                $sql .=  " from ($sql_1 UNION ALL $sql_2) a ";
            }
           //echo $sql;die;         
            $sql .= "LEFT JOIN maintenance_shops as shop ON a.shop_id=shop.id
            LEFT JOIN maintenance_supplier as ms ON ms.id = a.supplier
            LEFT JOIN supply_item as si on si.id=a.item_id
            LEFT JOIN supply_classification as sc3 on sc3.id=si.supply_classification_id
            LEFT JOIN supply_classification as sc2 on sc2.id=sc3.parent_id
            LEFT JOIN supply_classification as sc1 on sc1.id=sc2.parent_id
            
            WHERE  1=1 ";
            $order = " ORDER BY implement_time ASC ";

            if($shop_id != "") $sql .= " AND a.shop_id=$shop_id";
            if($supplier_id !="" ) $sql .= " AND ms.id=$supplier_id";
            if($level_1 != "")  $sql .= " AND sc1.id=$level_1";
            if($level_2 != "")  $sql .= " AND sc2.id=$level_2";
            if($level_3 != "")  $sql .= " AND sc3.id=$level_3";
            if($item != "" ) $sql .= " AND si.retrieval_code like '%".$item."%' ";
            if($brand != "") $sql .= " AND si.retrieval_code like '%".$brand."%' ";
            if ($supplier_str!="") $sql .= " AND ms.name like '%".$supplier_str."%' ";
            if ($supplier_city !="") $sql .= " AND ms.city_id=$supplier_city ";
            if ($supplier_region !="") $sql .= " AND ms.region_id=$supplier_region ";
            if ($supplier_status !="") $sql .= " AND ms.purchase_status=$supplier_status ";
            if ($shop_city !="") $sql .= " AND shop.city_id=$shop_city ";
            if ($shop_region !="") $sql .= " AND shop.region_id=$shop_region "; 
            
            $storage_list = DB::select( $sql.$order);
            //print_r($storage_list);die;
            $level_redio = [];
            $city_redio = [];
            $count = ["number" => 0, //签收总计
                    "tax_purchase_subtotal"=>0,//小计
                ];
            if (empty($storage_list)) {
                $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>"",'level_redio'=>$level_redio,'city_redio'=>$city_redio,'count'=> $count]);
                return $response;
                break;
            }

            foreach ($storage_list as $_list) {
                $_list->tax_purchase_price = round($_list->tax_purchase_price/100,2);
                $_list->no_tax_purchase_price = round($_list->no_tax_purchase_price/100,2);
                $_list->tax_purchase_subtotal = round($_list->tax_purchase_subtotal/100,2);
                //基础数据赋值
                if ($_list->list_type == 2) {
                    $_list->tax_purchase_price = 0 - $_list->tax_purchase_price;
                    $_list->no_tax_purchase_price = 0 - $_list->no_tax_purchase_price;
                    $_list->tax_purchase_subtotal = 0 - $_list->tax_purchase_subtotal;
                    $_list->number = 0 - $_list->number;
                }
                $count["number"] += $_list->number;
                $count["tax_purchase_subtotal"] += $_list->tax_purchase_subtotal; 
            }

            $level_redio = $this->storageLevelRedio($storage_list,$ratio_type,$count);
            $city_redio = $this->storageCityRedio($storage_list,$ratio_type,$count);
            
             $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>$storage_list,'pay_type'=>[0=>"现金",1=>"刷卡",2=>"挂账",3=>"其他"],'level_redio'=>$level_redio,'city_redio'=>$city_redio,'count'=>  $count]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "PMSStatis/StorageItemList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @deprecated 分类明细处理
     * @param $list 需要统计的数组
     * @param $type 统计的类型
     * @param $count 总数量的集合
     * 
     **/
    private function storageLevelRedio($list,$ratio_type,$count) {
        $level_redio = [];
        //$level_redio = ["level_1"][0]["name"=>"分类1"]["level_2"][0]["name"=>"分类2"][0]["name"=>"分类3"];
        $basic_arr = ["number"=> 0 , //定义每一层基本的结构
                    "tax_purchase_subtotal"=>0,
                    "name"=>"",
            ];
        foreach ($list as $_list) {
                //统计基础数据
                if (!isset($level_redio[$_list->sc1_id])) {
                    $level_redio[$_list->sc1_id]= $basic_arr;
                    $level_redio[$_list->sc1_id]["name"] = $_list->sc1_name;
                }
                if(!isset($level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id])){
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id] = $basic_arr;
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["name"] = $_list->sc2_name;
                }
                if (!isset($level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id])){
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id] = $basic_arr;
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id]["name"] = $_list->sc3_name;;
                } 
                    //三级   
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id]["number"] += $_list->number;
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["level_3"][$_list->sc3_id]["tax_purchase_subtotal"] += $_list->tax_purchase_subtotal;

                    //二级
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["number"] += $_list->number;
                    $level_redio[$_list->sc1_id]["level_2"][$_list->sc2_id]["tax_purchase_subtotal"] += $_list->tax_purchase_subtotal;

                    //一级
                    $level_redio[$_list->sc1_id]["number"] += $_list->number;
                    $level_redio[$_list->sc1_id]["tax_purchase_subtotal"] += $_list->tax_purchase_subtotal;   
                
        }
        
        if ($ratio_type == 1) { //上级占比 占上级总数的百分之多少
            foreach ($level_redio as $level_1_id => $level_1_value) {
                foreach ($level_1_value["level_2"] as $level_2_id => $level_2_value) {
                    foreach ($level_2_value["level_3"] as $level_3_id => $level_3_value) {
                        //三级签收统计
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_number"] = $count['number'] == 0 ? 0:
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["number"]/$count['number']*100);
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_tax_purchase_subtotal"] = $count['tax_purchase_subtotal'] == 0 ? 0:
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["tax_purchase_subtotal"]/$count['tax_purchase_subtotal']*100);
                    }
                    
                    //二级签收统计
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_number"] = $count['number'] == 0 ? 0 :
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["number"]/$count['number']*100);
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_tax_purchase_subtotal"] =  $count['tax_purchase_subtotal'] == 0 ? 0:
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["tax_purchase_subtotal"]/$count['tax_purchase_subtotal']*100);
                }
            //一级签收统计
            $level_redio[$level_1_id]["redio_number"] = $count['number']==0 ? 0 : round($level_redio[$level_1_id]["number"]/$count['number']*100);
            $level_redio[$level_1_id]["redio_tax_purchase_subtotal"] =  $count['tax_purchase_subtotal'] == 0 ? 0: round($level_redio[$level_1_id]["tax_purchase_subtotal"]/$count['tax_purchase_subtotal']*100); 
            }
        }
        
    
        if ($ratio_type == 2) {
            foreach ($level_redio as $level_1_id => $level_1_value) {
                foreach ($level_1_value["level_2"] as $level_2_id => $level_2_value) {
                    foreach ($level_2_value["level_3"] as $level_3_id => $level_3_value) {
                        //三级签收统计
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_number"] = $level_redio[$level_1_id]["level_2"][$level_2_id]["number"] == 0? 0:
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["number"]/$level_redio[$level_1_id]["level_2"][$level_2_id]["number"]*100);
                        $level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["redio_tax_purchase_subtotal"] = $level_redio[$level_1_id]["level_2"][$level_2_id]['tax_purchase_subtotal'] == 0? 0: 
                                round($level_redio[$level_1_id]["level_2"][$level_2_id]["level_3"][$level_3_id]["tax_purchase_subtotal"]/$level_redio[$level_1_id]["level_2"][$level_2_id]['tax_purchase_subtotal']*100);
                    
                    //二级签收统计
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_number"] = $level_redio[$level_1_id]['number'] == 0 ?0 :
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["number"]/$level_redio[$level_1_id]['number']*100);
                    $level_redio[$level_1_id]["level_2"][$level_2_id]["redio_tax_purchase_subtotal"] = $level_redio[$level_1_id]['tax_purchase_subtotal'] == 0 ? 0 :
                            round($level_redio[$level_1_id]["level_2"][$level_2_id]["tax_purchase_subtotal"]/$level_redio[$level_1_id]['tax_purchase_subtotal']*100);

                }
            //一级签收统计
            $level_redio[$level_1_id]["redio_number"] = 100;
            $level_redio[$level_1_id]["redio_tax_purchase_subtotal"] = 100;
                }
            }
        }
        $level_redio_object = [];
        //将数组转换成对象
            foreach ($level_redio as $level_1_id => $level_1_value) {
                $level_redio_object[$level_1_id] = $level_1_value;
                foreach ($level_1_value["level_2"] as $level_2_id => $level_2_value) {
                    $level_redio_object[$level_1_id]["level_2"][$level_2_id] = $level_2_value;
                    $level_redio_object[$level_1_id]["level_2"][$level_2_id]["level_3"] = array_values($level_2_value["level_3"]);
                }
                $level_redio_object[$level_1_id]["level_2"] = array_values($level_redio_object[$level_1_id]["level_2"]);
            }
        
        return array_values($level_redio_object);
        
    }
    /**
     * @deprecated 城市明细处理
     * @param $list 需要统计的数组
     * @param $type 统计的类型
     * @param $count 总数量的集合
     * 
     **/
    private function storageCityRedio($list,$ratio_type,$count) {
        $city_redio = [];
        $basic_arr = ["number"=> 0 , //定义每一层基本的结构
                    "tax_purchase_subtotal"=> 0,
                    "name"=>"",
            ];
        foreach ($list as $_list) {
                //统计基础数据
                if (!isset($city_redio[$_list->shop_city_id])) {
                    $city_redio[$_list->shop_city_id]= $basic_arr;
                    $city = DataResourceCity::where("id",$_list->shop_city_id)->first();
                    $city_redio[$_list->shop_city_id]["name"] = isset($city->city_name) ? $city->city_name :"";
                }
                if(!isset($city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id])){
                    $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id] = $basic_arr;
                    $region = DataResourceRegion::where("id",$_list->shop_region_id)->first();
                    $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["name"] = isset($region->region_name) ? $region->region_name:"";
                }
                if (!isset($city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id])){
                    $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id] = $basic_arr;
                    $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id]["name"] = $_list->shop_name;;
                } 
                //店 
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id]["number"] += $_list->number;
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["shop"][$_list->shop_id]["tax_purchase_subtotal"] += $_list->tax_purchase_subtotal;
                
                //区
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["number"] += $_list->number;
                $city_redio[$_list->shop_city_id]["region"][$_list->shop_region_id]["tax_purchase_subtotal"] += $_list->tax_purchase_subtotal;
                //市
                $city_redio[$_list->shop_city_id]["number"] += $_list->number;
                $city_redio[$_list->shop_city_id]["tax_purchase_subtotal"] += $_list->tax_purchase_subtotal;
                
        }
        
        if ($ratio_type == 1) { //上级占比 占上级总数的百分之多少
            foreach ($city_redio as $city_id => $city_value) {
                foreach ($city_value["region"] as $region_id => $region_value) {
                    foreach ($region_value["shop"] as $shop_id => $shop_value) {
                        //店 签收统计
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_number"] = $count['number'] == 0 ? 0:
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["number"]/$count['number']*100);
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_tax_purchase_subtotal"] = $count['tax_purchase_subtotal'] == 0 ? 0:
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["tax_purchase_subtotal"]/$count['tax_purchase_subtotal']*100);
                    }
                    
                    //区签收统计
                    $city_redio[$city_id]["region"][$region_id]["redio_number"] = $count['number'] == 0 ? 0 :
                            round($city_redio[$city_id]["region"][$region_id]["number"]/$count['number']*100);
                    $city_redio[$city_id]["region"][$region_id]["redio_tax_purchase_subtotal"] =  $count['tax_purchase_subtotal'] == 0 ? 0:
                            round($city_redio[$city_id]["region"][$region_id]["tax_purchase_subtotal"]/$count['tax_purchase_subtotal']*100);
                }
            //市签收统计
            $city_redio[$city_id]["redio_number"] = $count['number']==0 ? 0 : round($city_redio[$city_id]["number"]/$count['number']*100);
            $city_redio[$city_id]["redio_tax_purchase_subtotal"] =  $count['tax_purchase_subtotal'] == 0 ? 0: round($city_redio[$city_id]["tax_purchase_subtotal"]/$count['tax_purchase_subtotal']*100);
            }
        }
    
        if ($ratio_type == 2) {
            foreach ($city_redio as $city_id => $city_value) {
                foreach ($city_value["region"] as $region_id => $region_value) {
                    foreach ($region_value["shop"] as $shop_id => $shop_value) {
                        //店 签收统计
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_number"] = $city_redio[$city_id]["region"][$region_id]["number"] == 0? 0:
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["number"]/$city_redio[$city_id]["region"][$region_id]["number"]*100);
                        $city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["redio_tax_purchase_subtotal"] = $city_redio[$city_id]["region"][$region_id]['tax_purchase_subtotal'] == 0? 0: 
                                round($city_redio[$city_id]["region"][$region_id]["shop"][$shop_id]["tax_purchase_subtotal"]/$city_redio[$city_id]["region"][$region_id]['tax_purchase_subtotal']*100);
                    }
                    
                    //区签收统计
                    $city_redio[$city_id]["region"][$region_id]["redio_number"] = $city_redio[$city_id]['number'] == 0 ?0 :
                            round($city_redio[$city_id]["region"][$region_id]["number"]/$city_redio[$city_id]['number']*100);
                    $city_redio[$city_id]["region"][$region_id]["redio_tax_purchase_subtotal"] = $city_redio[$city_id]['tax_purchase_subtotal'] == 0 ? 0 :
                            round($city_redio[$city_id]["region"][$region_id]["tax_purchase_subtotal"]/$city_redio[$city_id]['tax_purchase_subtotal']*100);
                }
            //市签收统计
            $city_redio[$city_id]["redio_number"] = 100;
            $city_redio[$city_id]["redio_tax_purchase_subtotal"] = 100;
            }
        }
        
        $city_redio_object = [];
        //将数组转换成对象
            foreach ($city_redio as $city_id => $city_value) {
                $city_redio_object[$city_id] = $city_value;
                foreach ($city_value["region"] as $region_id => $region_value) {
                    $city_redio_object[$city_id]["region"][$region_id] = $region_value;
                    $city_redio_object[$city_id]["region"][$region_id]["shop"] = array_values($region_value["shop"]);
                }
                $city_redio_object[$city_id]["region"] = array_values($city_redio_object[$city_id]["region"]);
            }
        
        return array_values($city_redio_object);
    }
    
    
    /**
     *  订货月度分析
     * */
    public function monthStatice(){
        DB::connection()->disableQueryLog();      //关闭日志
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'tag' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $tag = Input::get("tag"); //标签 level_1一级分类,level_2二级分类,level_3三级分类,item商品SKU,shop门店汇总,
            $shop_id = Input::get("shop_id"); //门店id
            $supplier_str = Input::get("supplier_str");//供应商关键字搜索
            $brand = Input::get("brand");//品牌
            $date = Input::get("date")?:date("Y-m"); //要查询的月份

            switch($tag) {
                case "level_1": 
                    $order = " order by ms.id ASC,a.shop_id ASC,sc1.id ASC "; //排序的字段
                    $key = ['supplier','shop_id','sc1_id']; //用来分组的字段
                    $show = ['ms_name','shop_name','sc1_name']; //返回列表的字段
                    $result = $this->monthStaticeFun($key, $show, $order,$date,$shop_id,$supplier_str,$brand);
                    break;
                case "level_2": 
                    $order = " order by ms.id ASC,a.shop_id ASC,sc2.id ASC "; //排序的字段
                    $key = ['supplier','shop_id','sc2_id']; //用来分组的字段
                    $show = ['ms_name','shop_name','sc2_name']; //返回列表的字段
                    $result = $this->monthStaticeFun($key, $show,$order,$date,$shop_id,$supplier_str,$brand);
                    break;
                case "level_3": 
                    $order = " order by ms.id ASC,a.shop_id ASC,sc3.id ASC "; //排序的字段
                    $key = ['supplier','shop_id','sc3_id']; //用来分组的字段
                    $show = ['ms_name','shop_name','sc3_name']; //返回列表的字段
                    $result = $this->monthStaticeFun($key, $show, $order,$date,$shop_id,$supplier_str,$brand);
                    break;
                case "item": 
                    $order = " order by ms.id ASC,a.shop_id ASC,code ASC "; //排序的字段
                    $key = ['supplier','shop_id','si_id']; //用来分组的字段
                    $show = ['ms_name','shop_name','code','si_brand_name','si_name']; //返回列表的字段
                    $result = $this->monthStaticeFun($key, $show, $order,$date,$shop_id,$supplier_str,$brand);
                    break;
                case "shop": 
                    $order = " order by a.shop_id ASC "; //排序的字段
                    $key = ['shop_id']; //用来分组的字段
                    $show = ['shop_name']; //返回列表的字段
                    $result = $this->monthStaticeFun($key, $show, $order,$date,$shop_id,$supplier_str,$brand);
                    break;
                default :
                    $order = " order by ms.id ASC,a.shop_id ASC,sc1.id ASC "; //排序的字段
                    $key = ['supplier','shop_id','sc1_id']; //用来分组的字段
                    $show = ['ms_name','shop_name','sc1_name']; //返回列表的字段
                    $result = $this->monthStaticeFun($key, $show, $order,$date,$shop_id,$supplier_str,$brand);        
                    break;
            }
             $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        }while(false);
        return json_encode($response);
    }
    
    
    /**
     *  订货月度分析
     * */
    private function monthStaticeFun($key,$show,$order,$date,$shop_id,$supplier_str,$brand){
            $date_start = $date."-01 00:00:00";
            $date_end = date('Y-m-t', strtotime("$date_start +1 month -1 day")) . " 23:59:59";

            //上月
            $before_month_start = date('Y-m-d 00:00:00', strtotime($date_start . '-1 month'));
            $before_month_end = date('Y-m-t 23:59:59', strtotime($date_start . '-1 month'));
            $before_month_data = $this->MonthData($before_month_start, $before_month_end, $shop_id, $supplier_str, $brand,'');
            $before_month_data = $this->groupField($before_month_data,$key);

            //去年
            $before_year_start = date('Y-m-d 00:00:00', strtotime($date_start . '-12 month'));
            $before_year_end = date('Y-m-t 23:59:59', strtotime($date_start . '-12 month'));
            $before_year_data = $this->MonthData($before_year_start, $before_year_end, $shop_id, $supplier_str, $brand,'');
            $before_year_data = $this->groupField($before_year_data,$key);
            $new_array = [];
            $in_number = 0 ;//入库数量
            $in_purchase_price = 0; //入库金额
            $out_number = 0 ; //退货数量
            $out_purchase_price = 0; //退货金额
            $all_number = 0;//全部数量
            $all_purchase_price = 0;//全部金额
            //
            //本月
            $this_month_data = $this->MonthData($date_start, $date_end, $shop_id, $supplier_str, $brand,$order);
            //print_r($this_month_data);die;
            //循环本月份，进行集合统计
            foreach ($this_month_data as $k=>$value) {
                if ($value->shop_id == 2) continue;
                $data_k = "";
                 foreach ($key as $k) {
                     $data_k .= $value ->$k."_";
                 }
                 $data_k = rtrim($data_k,'_');

                 $value->tax_purchase_price = round($value->tax_purchase_price/100,2);

                 if (!isset($new_array[$data_k])) {
                     foreach ($show as $v){
                        $new_array[$data_k][$v] =  $value->$v; 
                     }

                     $new_array[$data_k]['in_number'] = 0; //入库数量
                     $new_array[$data_k]['in_purchase_price'] = 0; //入库金额
                     $new_array[$data_k]['out_number'] = 0; //退货数量
                     $new_array[$data_k]['out_purchase_price'] = 0;//退货金额
                     $new_array[$data_k]['this_month_number'] = 0; //这月数量
                     $new_array[$data_k]['this_month_money'] = 0; //这月金额
                     $new_array[$data_k]['before_month_number'] = 0; //上月数量
                     $new_array[$data_k]['before_month_money'] = 0; //上月金额
                     $new_array[$data_k]['before_year_number'] = 0; //去年数量
                     $new_array[$data_k]['before_year_money'] = 0; //去年金额
                     
                     if (isset($before_month_data[$data_k])) {//上月数据
                         $new_array[$data_k]['before_month_number'] = $before_month_data[$data_k]['number'];
                         $new_array[$data_k]['before_month_money'] = $before_month_data[$data_k]['money'];
                         unset($before_month_data[$data_k]);
                     }
                     if (isset($before_year_data[$data_k])) {//去年数据
                         $new_array[$data_k]['before_year_number'] = $before_year_data[$data_k]['number'];
                         $new_array[$data_k]['before_year_money'] = $before_year_data[$data_k]['money'];
                         unset($before_month_data[$data_k]);
                     }
                 }
                 
                 $price = $value->number * $value->tax_purchase_price;
                 if ($value->list_type == 1) {
                     $new_array[$data_k]['in_number'] += $value->number;
                     $new_array[$data_k]['in_purchase_price'] += $price;
                     
                     //当前月的总结
                     $new_array[$data_k]['this_month_number'] += $value->number;
                     $new_array[$data_k]['this_month_money'] += $price;
                     //所有入库汇总
                     $in_number += $value->number;
                     $in_purchase_price += $price;
                     //全部汇总
                     $all_number += $value->number;
                     $all_purchase_price += $price;
                 }else{
                     $new_array[$data_k]['out_number'] -= $value->number;
                     $new_array[$data_k]['out_purchase_price'] -= $price;
                     //当前月的总结
                     $new_array[$data_k]['this_month_number'] -= $value->number;
                     $new_array[$data_k]['this_month_money'] -= $price;
                      //所有退货汇总
                     $out_number -= $value->number;
                     $out_purchase_price -= $price;
                     //全部汇总
                     $all_number -= $value->number;
                     $all_purchase_price -= $price;
                 }
            }
            //最终价格处理
            foreach($new_array as &$v) {
                $v['in_purchase_price'] = round($v['in_purchase_price'],2);
                $v['out_purchase_price'] = round($v['out_purchase_price'],2);
                $v['this_month_money'] = round($v['this_month_money'],2);
                $v['before_month_money'] = round($v['before_month_money'],2);
                $v['before_year_money'] = round($v['before_year_money'],2);
            }
            $in_purchase_price = round($in_purchase_price,2); //入库金额
            $out_purchase_price = round($out_purchase_price,2);; //退货金额
            $all_purchase_price = round($all_purchase_price,2);;//全部金额
            
            $new_array = array_values($new_array);
            $before_year = date('Y-m',  strtotime($before_year_start));
            $before_month = date('Y-m',  strtotime($before_month_start));
            
            return ['list' => $new_array,'in_number'=>$in_number,'in_purchase_price'=>$in_purchase_price,'out_number'=>$out_number,'out_purchase_price'=>$out_purchase_price,'all_number'=>$all_number,'all_purchase_price'=>$all_purchase_price,'date'=>$date,'before_month'=>$before_month,'before_year'=>$before_year];
    }
    
    //获取当前月的数据
    function MonthData($date_start,$date_end,$shop_id,$supplier_str,$brand,$order){
            $cache_key = "MonthData_{$date_start}_{$date_end}_{$shop_id}_{$supplier_str}_{$brand}";
            if(Cache::has($cache_key)){//如果有缓存的 入库 退货 集合
                $storage_list = Cache::get($cache_key);
                return $storage_list;
            }
            //入库单 list_type = 1
            $sql_1 = "select msi.id,msi.item_id,maintenance_storage_list.shop_id,msi.`code`,msi.`name`,msi.number,msi.tax_purchase_price,1 as list_type,maintenance_storage_list.supplier
            FROM maintenance_storage_item msi
            LEFT JOIN maintenance_storage_list ON msi.list_id = maintenance_storage_list.id
            WHERE  `maintenance_storage_list`.`implement_time` BETWEEN '".$date_start."' AND '".$date_end."' AND `maintenance_storage_list`.`status` = 1 
            AND `msi`.`status` = 1 
            AND `maintenance_storage_list`.`type` IN (1, 2)";  //入库单
            
            //退货单 list_type = 2
            $sql_2 = "SELECT  moi.id,moi.item_id,maintenance_out_list.shop_id,moi.`code`,moi.`name`,moi.number,moi.tax_purchase_price,2 as list_type,maintenance_out_list.consuming_id as supplier
            FROM
                maintenance_out_item moi
            LEFT JOIN maintenance_out_list ON moi.list_id = maintenance_out_list.id
            WHERE
                maintenance_out_list.implement_time BETWEEN '".$date_start."' AND '".$date_end.
            "' AND `maintenance_out_list`.`status` = 1
            AND `moi`.`status` = 1
            AND `maintenance_out_list`.`type` = 2
            AND `maintenance_out_list`.`out_type` = 2";   //退货单
            //入库单相关
            $sql = "SELECT a.*,sc3.name as sc3_name,sc3.id as sc3_id,sc2.name as sc2_name,sc2.id as sc2_id,sc1.name as sc1_name,sc1.id as sc1_id,si.name as si_name,si.id as si_id,si.brand_name as si_brand_name,si.brand_id as si_brand_id,si.code as si_code,ms.name as ms_name,shop.name as shop_name";

            $sql .=  " from ($sql_1 UNION ALL $sql_2) a ";

            $sql .= "LEFT JOIN maintenance_shops as shop ON a.shop_id=shop.id
            LEFT JOIN maintenance_supplier as ms ON ms.id = a.supplier
            LEFT JOIN supply_item as si on si.id=a.item_id
            LEFT JOIN supply_classification as sc3 on sc3.id=si.supply_classification_id
            LEFT JOIN supply_classification as sc2 on sc2.id=sc3.parent_id
            LEFT JOIN supply_classification as sc1 on sc1.id=sc2.parent_id
            
            WHERE  1=1 ";

            if($shop_id != "") $sql .= " AND a.shop_id=$shop_id";
            if($brand != "") $sql .= " AND si.brand_id = $brand";
            if ($supplier_str!="") $sql .= " AND ms.name like '%".$supplier_str."%' ";
            
            $storage_list = DB::select( $sql.$order);
            Cache::add($cache_key,$storage_list, 5);
            return $storage_list;
    }

    function groupField($data,$key) {
        $new_array = [];
        foreach ($data as $value) {
            $data_k = "";
            foreach ($key as $k) {
                $data_k .= $value ->$k."_";
            }
            $data_k = rtrim($data_k,'_');
            
            $value->tax_purchase_price = round($value->tax_purchase_price/100,2);
            //基础数据赋值
            if ($value->list_type == 2)  $value->number = 0 - $value->number;
            
            if (!isset($new_array[$data_k])) {
                $new_array[$data_k]['number'] = $value->number;
                $new_array[$data_k]['money'] = $value->number * $value->tax_purchase_price;      
            }else{
                $new_array[$data_k]['number'] += $value->number;
                $new_array[$data_k]['money'] += $value->number * $value->tax_purchase_price;  
            }
        }
        unset($data);
        return $new_array;
    }
    
    /**
     * @Description:     获取耗材品牌列表
     */
    public function supplyBrandList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'num' => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $name   = Input::get('name', '');   //品牌名称[支持模糊查询]
            $num    = Input::get('num', 0);     //一次展示的数量 [ 默认为全部 ]
            
            $list = DataSupplyBrand::select('id', 'initial', 'brand_name')->where('status', 1)->orderBy('id', 'ASC');
            if($name != ''){
                $list->where('brand_name', 'like', '%'.$name.'%');
            }
            if($num != 0){
                $list = $list->skip(0)->take($num)->get();
            } else {
                $list = $list->get();
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ['count' => count($list), 'list' => $list]);
        }while(false);
        
        Log::info("info", array("system" => "scs" ,"event" => "PMSStatis/supplyBrandList", 'input' =>Input::all() ,"output" => $response));
        
        return json_encode($response);
    }
    
}


